package threadlocal_test;


import java.util.Random;

/**
 * @author Ajie
 * @date 2019-10-11
 * @function
 *
 * https://blog.csdn.net/Oeljeklaus/article/details/80545749
 *
 * ThreadLocal的确是数据的隔离，但是并非数据的复制，而是在每一个线程中创建一个新的数据对象，然后每一个线程使用的是不一样的。
 *
 * todo 因为没有init 新的对象造成 threadlocal 失效。
 */
public class ThreadLocal01 {
    public static void main(String[] args) {
        final MPerson p=new MPerson();
        //这样就针对于每一个线程创建一个独立的MPerson对象
        final ThreadLocal<MPerson> threadLocal=new ThreadLocal<MPerson>(){
            public MPerson initialValue() {
                return new MPerson();
            }
        };

        final ThreadLocal<String> threadLocalStr=new ThreadLocal<String>(){
            public String initialValue() {
                return new Random().nextInt(100)+"";
            }
        };


        for(int i=0;i<1;i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    java.lang.Thread thread = java.lang.Thread.currentThread();

                    threadLocal.get().setName(new Random().nextInt(100)+"");
                    System.out.println("thread : "+ thread.getName()+" getname== "+threadLocal.get().getName()+"  threadLocal.get对象: "+ threadLocal.get());

//                    threadLocal.remove();//TODO 删除了 这个副本

                    threadLocal.get().setName(new Random().nextInt(100)+"");
                    System.out.println("thread22 : "+ thread.getName()+" getname== "+threadLocal.get().getName()+"  threadLocal.get对象: "+ threadLocal.get());


                    System.err.println("thread str : "+ thread.getName()+" getname== "+threadLocalStr.get()+"  threadLocal.get对象: "+ threadLocal.get());
                    threadLocalStr.set("1231 www");
                    System.err.println("thread str 22 : "+ thread.getName()+" getname== "+threadLocalStr.get()+"  threadLocal.get对象: "+ threadLocal.get());

                }
            }).start();
        }

    }
}


class MPerson {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) throws InterruptedException {

    }
}

